package com.daydayup.calculator;

import java.math.BigDecimal;
import java.util.Scanner;

public class Calculator {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.println("请输入第一个数字：");
		BigDecimal num1 = scanner.nextBigDecimal();
		System.out.println("请输入运算符号：");
		String sign = scanner.next();
		System.out.println("请输入第二个数字：");
		BigDecimal num2 = scanner.nextBigDecimal();
		System.out.println("请输入计算结果保留的小数点位数：");
		int point = scanner.nextInt();
		scanner.close();
		BigDecimal value = null;
		try {
			value = calculat(num1, sign, num2, point);
		} catch (Exception e) {
			System.out.println(e.getMessage());
			return;
		}
		System.out.println("计算结果为：" + num1.toString() + sign + num2.toString() + " = " + value.toString());

	}

	private static BigDecimal calculat(BigDecimal num1, String sign, BigDecimal num2, int point) throws Exception {
		switch (sign) {
		case "+":
			return num1.add(num2).setScale(point, BigDecimal.ROUND_HALF_UP);
		case "-":
			return num1.subtract(num2).setScale(point, BigDecimal.ROUND_HALF_UP);
		case "*":
			return num1.multiply(num2).setScale(point, BigDecimal.ROUND_HALF_UP);
		case "/":
			if (num2.doubleValue() == 0) {
				throw new Exception("除数不能为0");
			}
			return num1.divide(num2, point, BigDecimal.ROUND_HALF_UP);
		default:
			throw new Exception("符号不正确！");
		}
	}

}
